package com.jonluo.controller;

import com.alibaba.fastjson.JSONObject;
import com.google.code.kaptcha.Producer;
import com.jonluo.common.utils.EnvVariable;
import com.jonluo.common.utils.R;
import com.jonluo.common.utils.RedisUtils;
import com.jonluo.common.utils.ShiroUtils;
import com.jonluo.entity.UserEntity;
import com.jonluo.entity.UserTokenEntity;
import com.jonluo.oauth2.TokenGenerator;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录相关
 * @author com.jonluo
 * Date 2017/9/15
 */
@RestController
public class LoginController {
	@Autowired
	private Producer producer;
	@Autowired
	RestTemplate restTemplate;
	@Autowired
	EnvVariable envVariable;
	@Autowired
	RedisUtils redisUtils;


	/**
	 * 验证码
	 * @param response
	 * @throws ServletException
	 * @throws IOException
     */
	@RequestMapping("captcha.jpg")
	public void captcha(HttpServletResponse response)throws ServletException, IOException {
		response.setHeader("Cache-Control", "no-store, no-cache");
		response.setContentType("image/jpeg");
		//生成文字验证码
		String text = producer.createText();
		//生成图片验证码
		BufferedImage image = producer.createImage(text);
		//保存到shiro session
		ShiroUtils.setKaptcha(text);

		ServletOutputStream out = response.getOutputStream();
		ImageIO.write(image, "jpg", out);
		IOUtils.closeQuietly(out);
	}

	/**
	 * 登录
	 */
	@RequestMapping(value = "/sys/login", method = RequestMethod.POST)
	public Map<String, Object> login(String username, String password, String captcha)throws IOException {
		String kaptcha = ShiroUtils.getKaptcha();
		if(!captcha.equalsIgnoreCase(kaptcha)){
			return R.error("验证码不正确");
		}

		//用户信息
		UserEntity user = null ;
		String resultJson = restTemplate.getForEntity(envVariable.getBaseUrl()+"/user/getByUserName/"+username, String.class).getBody();
		JSONObject resultMap = JSONObject.parseObject(resultJson);
		if ( 0 == resultMap.getInteger("code")){
			user = resultMap.getObject("data",UserEntity.class);
		}
		//账号不存在、密码错误
		if(user == null || !user.getPassword().equals(new Sha256Hash(password, user.getSalt()).toHex())) {
			return R.error("账号或密码不正确");
		}

		//账号锁定
		if(user.getStatus() == 0){
			return R.error("账号已被锁定,请联系管理员");
		}

		//生成token，并保存到redis
		 Map<String,Object> map = createToken(user.getUserId());
		return R.ok().put("token", map.get("token")).put("expire", map.get("expire"));
	}


	public Map<String,Object> createToken(String userId){
		//生成一个token
		String token = TokenGenerator.generateValue();
		//当前时间
		Date now = new Date();
		//过期时间
		Date expireTime = new Date(now.getTime() + RedisUtils.DEFAULT_EXPIRE * 1000);
		//生成过token实体
		UserTokenEntity tokenEntity = new UserTokenEntity();
		tokenEntity.setUserId(userId);
		tokenEntity.setToken(token);
		tokenEntity.setUpdateTime(now);
		tokenEntity.setExpireTime(expireTime);
		//保存token
		redisUtils.set(token,tokenEntity);

		Map<String,Object> map = new HashMap<String, Object>();
		map.put("token",token);
		map.put("expire", RedisUtils.DEFAULT_EXPIRE);
		return map;
	};
}
